<template>
  <el-dialog
          :title="title"
          :visible.sync="showDialog" onclose="close">
    <el-form label-position="top">
      <el-form-item label="批量录入（每行格式：IP 用户 密码）">
        <el-input type="textarea" v-model="vps.value" @change="processValue" :rows="5"/>
      </el-form-item>
      <el-form-item label="预览">
        <el-table :data="vps.list" stripe border height="250">
          <el-table-column label="IP" prop="ip"/>
          <el-table-column label="用户" prop="user"/>
          <el-table-column label="密码" prop="password"/>
        </el-table>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showDialog = false">取 消</el-button>
      <el-button type="primary" @click="submit">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    name: 'vpsBulkCreate',
    data() {
      return {
        vps: {value: '', list: []},
        showDialog: false,
      };
    },
    methods: {
      show() {
        this.showDialog = true;
      },
      close() {
        Object.assign(this.$data, this.$options.data());
      },
      processValue(val) {
        this.vps.list = val.split('\n').map(line => {
          const match = line.match(/\s*(\S+)\s+(\S+)\s+(\S+)/);
          if (match && match.length === 4)
            return {ip: match[1], user: match[2], password: match[3]};
          return null;
        }).filter(vps => !!vps);
      },
      async submit() {
        if (this.vps.list.length === 0)
          return;
        const sure = await new Promise(
            resolve => {
              this.$confirm('确认无误？', {type: 'warning'}).then(() => {
                resolve(true);
              }).catch(() => {
                resolve(false);
              });
            });
        if (!sure)
          return;
        const res = await this.$http.post('/api/vps/bulk-create', this.vps.list);
        if (res instanceof Error)
          return this.$alert(res.message, {type: 'error'});
        this.$message({message: '操作成功', type: 'success'});
        this.$emit('success');
        this.close();
      },
    },
    computed: {
      title() {
        if (this.client && this.client.id)
          return '编辑服务器';
        return '添加服务器';
      },
    },
    mounted() {
    },
  };
</script>

<style scoped>

</style>